package com.yang.leather.common.upload;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.tepando.upload.Config;
import com.tepando.upload.images.ImageType;
import com.yang.leather.admin.pojo.ImgsDel;
import com.yang.leather.common.store.IFileService;
import com.yang.leather.common.store.image.ImageUtils;
import com.yang.leather.common.struts2.ContextPvd;

@Service("uploadService")
public class UploadServiceImpl implements IUploadService{
	
	private ContextPvd contextPvd;
	
	private IFileService fileService;
	
	public String uploadByType(HttpServletRequest request,String fileFileName,String uploadRuleId,String uploadType) throws UploadException{
		if(ImageUploadType.PROD_DETAIL.getType().equals(uploadType)){//商品详情
			return upload(request,fileFileName,ImageUploadType.PROD_DETAIL,uploadRuleId,true,null);
		}
		return null;
	}
	
	public String uploadProduct(HttpServletRequest request, String fileFileName, String uploadRuleId) throws UploadException {
		return upload(request,fileFileName,ImageUploadType.PRODUCT,uploadRuleId,true,null);
	}
	
	/**
	 * 
	 * @param request
	 * @param fileFileName form表单文件name
	 * @param uploadType 上传类型
	 * @param uploadRuleId 上传规则ID，编辑框上传图片才传入uploadRuleId
	 * @param isNeed 可传可不传文件 ture为传文件
	 * @param imageType 图片尺寸定义
	 * 
	 * return 文件路径
	 */
	private String upload(HttpServletRequest request,String fileFileName,ImageUploadType uploadType, 
			String uploadRuleId,boolean isNeed,ImageType imgType) throws UploadException{
		if(request==null || StringUtils.isEmpty(fileFileName) || uploadType==null){
			throw new UploadException(ARGUMENT_INVALID,"参数不合法!");
		}
		UploadRule rule = null;
		if(isNeed){
			rule = (UploadRule)contextPvd.getSessionAttr(UploadRule.KEY + uploadRuleId);
			if(rule==null){
				throw new UploadException(NO_RULE_ID,"没有上传规则");
			}
		}
		
		if (request!=null && request instanceof MultiPartRequestWrapper) {
			MultiPartRequestWrapper mRequest = (MultiPartRequestWrapper) request;
			if(mRequest.hasErrors()){
				throw new UploadException(FILE_SIZE_ERROR,"上传图片尺寸太大!");
			}
			
			try {
				File[] files = mRequest.getFiles(fileFileName);
				String[] fileNames = mRequest.getFileNames(fileFileName);
				if(files!=null){
					for(String fileName : fileNames){
						String ext = FilenameUtils.getExtension(fileName);
						if (!ImageUtils.isValidImageExt(ext)) {
							throw new UploadException(NOT_SUPPORT_IMG_EXT,"不支持上传的文件,请上传jpg,jpeg,gif,png,bmp图片");
						}
					}
					for(File file : files){
						if(!ImageUtils.isImage(new FileInputStream(file))){
							throw new UploadException(NOT_IMAGE,"上传的不是图片!");
						}
						
						
					}
				}else{
					if(!isNeed){
						return null;
					}else{
						throw new UploadException(FILE_ISNULL,"请上传图片!");
					}
				}
				
				if(imgType==null){
					imgType = this.getImgType(uploadType);
					if(imgType == null || imgType.getSizes()==null || imgType.getSizes().size()==0){
						throw new UploadException(NO_IMG_TYPE,"请定义图片尺寸!");
					}
				}
				
				String strReponse = fileService.store(files, imgType, uploadType);
				StringBuilder realFilePath = new StringBuilder();
				for(String f : strReponse.split(";")){
					String[] fs = f.split(",");
					if(fs.length!=2){
						throw new UploadException(APPLICATION_ERROR,"应用程序错误");
					}
					String filePath = fs[0];
					String fileName = fs[1];
					
					if(realFilePath.length()> 0){
						realFilePath.append(";");
					}
					realFilePath.append(fs[0]+fs[1]);
					
					if(isNeed){
						rule.addUploadFile(filePath,fileName);
					}
				}
				
				return realFilePath.toString();
			} catch (Exception e) {
				throw new UploadException(APPLICATION_ERROR,e.getMessage());
			} 
		}
		return null;
	}
	
	private ImageType getImgType(ImageUploadType uploadType){
		return Config.Image.getType(uploadType.getTypeId());
	}

	public String deleteFile(List<ImgsDel> lstImgsDel){
		
		return "success";
	}
	
	public ContextPvd getContextPvd() {
		return contextPvd;
	}

	@Autowired
	public void setContextPvd(@Qualifier("contextPvd")
			ContextPvd contextPvd) {
		this.contextPvd = contextPvd;
	}

	public IFileService getFileService() {
		return fileService;
	}

	@Autowired
	public void setFileService(@Qualifier("diskFileService")
			IFileService fileService) {
		this.fileService = fileService;
	}
}
